home *** CD-ROM | disk | FTP | other *** search
- Path: news.compuserve.com!newsmaster
- From: <75151.03563@compuserve.com>
- Newsgroups: comp.lang.c++
- Subject: RE: Copt constructing an already default ....
- Date: 26 Jan 1996 02:15:23 GMT
- Organization: CompuServe Incorporated
- Message-ID: <4e9dfr$spc@dub-news-svc-6.compuserve.com>
- NNTP-Posting-Host: dd35-159.compuserve.com
- Content-Type: text/plain
- Content-length: 1412
- X-Newsreader: AIR Mosaic (16-bit) version 3.10.08.25
-
-
- > I've go an object which has already been constructed via its default
- > constructor which just sets all pointers to NULL. What's the best
- > way to deep-copy into it ??
-
- How about:
-
- Class A{
- public:
- A();
- A( const A & a ) { deepCopy( a ); }
-
- A & operator= (const A & a ) { deepCopy( a ); return *this; }
-
- protected:
- void deepCopy( const A & );
-
- private:
- char * m_pData;
- int m_nDataSize;
- };
-
- void A::deepCopy( const A & a )
- {
- // perform deep copy here
-
- // avoid self-assingment...
- if ( a.m_pData == m_pData )
- return;
-
- char * tmp= new char[ a.m_nDataSize ];
- if (tmp == NULL)
- return;
-
- m_pData= tmp;
- m_nDataSize= a.m_nDataSize;
-
- memmove( m_pData, a.m_pData, m_nDataSize );
- }
-
-
- The way you implemented a deep-copy assignment operator :
- >>
- >> A & A::operator=( const A & other )
- >> {
- >> A empty;
- >> A tmp( other );
- >> memcpy( this, &tmp, sizeof( A ) );
- >> memcpy( &tmp, &empty, sizeof( A ) );
- >> return *this;
- >> }
- >>
-
- jumps through unnecessary hoops, and is dangerous. It is not a good
- idea to memcpy() to an object. If the object has no virtual functions
- you will usually be OK, but if the class does have virtual functions, you
- will most likely over-write the virtual function table pointer and
- completely hose yourself.
-
- Hope this Helps,
-
- Tom Keane
- 75151,03563
-
-